package com.wwz.leetcode;

import org.junit.Test;

/**
 * 用时 10:27
 */
public class LeetCode200_1 {
    @Test
    public void test() {
        char[][] grid = {
                {'1', '1', '0', '1', '1'},
                {'1', '1', '0', '1', '1'},
                {'0', '0', '0', '0', '0'},
                {'0', '0', '1', '0', '0'}
        };
        System.out.println(numIslands(grid));
    }

    // 计算岛屿数量
    public int numIslands(char[][] grid) {
        int count = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] == '1') {
                    dfsGrid(grid, i, j);
                    count++;
                }

            }
        }
        return count;
    }

    public void dfsGrid(char[][] grid, int i, int j) {
        // 判断在不在网格里面
        if (i < 0 || j < 0 || i >= grid.length || j >= grid[0].length) {
            return;
        }
        if (grid[i][j] == '1') {
            // 标记已经访问过的陆地
            grid[i][j] = '2';
            // 向下
            dfsGrid(grid, i + 1, j);
            // 向右
            dfsGrid(grid, i - 1, j);
            // 向上
            dfsGrid(grid, i, j + 1);
            // 向左
            dfsGrid(grid, i, j - 1);
        }

    }

}
